import { Object3D } from 'three-legacy';
import { MeasureLabelPositions, MeasureRenders, MeasureResult } from './types';
import { renderMeasureResult } from '.';

export class MeasureObject extends Object3D {
  constructor(public measureResult: MeasureResult) {
    super();
  }

  private parsedResults: MeasureRenders = {};

  private _isDestroyed = false;
  async render() {
    this.parsedResults = await renderMeasureResult(this.measureResult);

    if (this._isDestroyed) {
      Object.values(this.parsedResults).forEach((o) => o.destroy());
    } else {
      Object.values(this.parsedResults).forEach((o) => this.add(o));
    }
  }

  destroy() {
    this._isDestroyed = true;
    Object.values(this.parsedResults).forEach((c) => c.destroy());
    this.parent?.remove(this);
  }

  isHovered: boolean;
  isSelected: boolean;

  setHover(val: boolean) {
    this.isHovered = val;
    this.children.forEach((c) => (c as any).setHover?.(val));
  }
  setSelect(val: boolean) {
    this.isSelected = val;
    this.children.forEach((c) => (c as any).setSelect?.(val));
  }

  getLabelPositions() {
    const result: MeasureLabelPositions = {
      length: this.parsedResults.length?.endPosition?.toArray(),
      radius: this.parsedResults.radius?.endPosition?.toArray(),
      minDistance: this.parsedResults.minDistance?.getLabelPositions(),
      centerDistance: this.parsedResults.centerDistance?.getLabelPositions(),
      angle:
        this.parsedResults.angle?.label?.measureLabel?.endPosition?.toArray(),
      area: this.parsedResults.area?.endPosition?.toArray(),
      round: this.parsedResults.round?.endPosition?.toArray(),
    };

    return result;
  }
}
